package com.leyou.gateway.filter;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.util.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class AuthFilter extends ZuulFilter {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private FilterProperties filterProp;
    /**
     * 过滤器类型  前置过滤
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER -1;
    }

    /**
     * 是否过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获得上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获得request
        HttpServletRequest request = ctx.getRequest();

        //获得请求的url路径
        String path = request.getRequestURI();



        //判断请求的地址是否在白名单中，如果在则放行 返回false
        return !isAllowPath(path);
    }

    private boolean isAllowPath(String path) {
        for (String allowPath : filterProp.getAllowPaths()) {
            if(path.startsWith(allowPath)){
                return  true;
            }
        }

        return  false;
    }

    /**
     * 过滤逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获得上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获得request
        HttpServletRequest request = ctx.getRequest();

        //获取cookie中的token
        String token = CookieUtils.getCookieValue(request, prop.getCookieName());
        try {
            //解析token
            UserInfo userInfo = JwtUtils.getUserInfo(prop.getPublicKey(), token);
            // 校验权限
        }catch (Exception e){
            //解析失败  未登录 进行拦截
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);

        }
        return  null;
    }
}
